<template>
    <div class="map-top">
      <div class="top">
      <div class="top-back" @click="homeback">
        <img src="@/assets/back.png" alt="" /> 返回
      </div>
      <p>城市定位</p>
    </div>
    <div class="map-serach">
      <van-search
        v-model="value"
        placeholder="请输入搜索关键词"
        shape="round"
      />
    </div>

    <div class="search-list">
      <div
        class="search-item"
        v-for="item in list"
        :key="item.id"
        @click="tabEvents(item)"
      >
        <p>{{ item.name }}</p>
        <img src="@/assets/go.png" alt="" />
      </div>
    </div>

    <div class="map-content">
      <p class="current">当前位置:</p>
      <div id="container"></div>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapState } from "vuex";
export default {
  name: "Index",

  data() {
    return {
      value: "",
      city: "",
      list: [],
      citymap: {},
    };
  },
  computed: {
    ...mapState(["cityInfo"]),
  },

  watch: {
    value() {
      var _this = this;
      AMap.plugin("AMap.AutoComplete", function () {
        // 实例化Autocomplete
        var autoOptions = {
          //city 限定城市，默认全国
          city: _this.city,
        };
        var autoComplete = new AMap.AutoComplete(autoOptions);
        autoComplete.search(_this.value, function (status, result) {
          // 搜索成功时，result即是对应的匹配数据
          console.log(result);
          _this.list = result.tips;
        });
      });
    },
  },

  mounted() {
    var _this = this;
    if (this.cityInfo.name) {
      var map = new AMap.Map("container", {
        zoom: 17,
        center: [this.cityInfo.location.lng, this.cityInfo.location.lat],
      });
      var marker = new AMap.Marker({
        position: [this.cityInfo.location.lng, this.cityInfo.location.lat], //位置
      });

      // 创建纯文本标记
      var text = new AMap.Text({
        text: `${this.cityInfo.name}`,
        anchor: "center", // 设置文本标记锚点
        cursor: "pointer",
        position: [this.cityInfo.location.lng, this.cityInfo.location.lat],
      });

      text.setMap(map);

      map.add(marker); //添加到地图
    } else {
      var map = new AMap.Map("container", {
        zoom: 10, // 缩放级别
      });
    }
  },

  methods: {
    ...mapMutations(["upCityInfo"]),

    homeback() {
      this.$router.push({ name: "home" });
    },
    tabEvents(val) {
      this.upCityInfo(val);
      this.$router.push("/home");
    },
  },
};
</script>

<style scoped lang="scss">
@import "../scss/map/index.scss";
* {
  margin: 0;
  padding: 0;
}
</style>